Popular Searches
Popular Course Categories
Popular Courses

Working with Assignment and Compound Assignment Operators

Working with Assignment and Compound Assignment Operators

Operators and Expressions in Python

Working with Assignment and Compound Assignment Operators in Python

Course: Python Training Course

Topic: Working with Assignment and Compound Assignment Operators

Course Link: Python Training Course – JustAcademy

Demo Registration: Register for a Course Demo

Website: Visit JustAcademy


1. Introduction to Assignment Operators in Python

Assignment operators are fundamental components of Python programming. They are used to assign values to variables, update existing values, and store the results of calculations. Assignment operations appear in almost every Python program, from simple scripts to advanced applications involving data processing, automation, web development, and analytics.

The basic assignment operator is the equal sign (=). It assigns the value on its right-hand side to the target on its left-hand side. Python also provides compound assignment operators, such as +=, -=, *=, and /=, which combine an operation with assignment.

Understanding these operators helps programmers write concise, readable, and maintainable code. They are especially useful when calculating totals, updating counters, tracking balances, modifying variables inside loops, and accumulating results.

Example

number = 10
print(number)

number += 5
print(number)

Output:

10
15

In this example, the first statement assigns 10 to the variable number. The second statement adds 5 to its current value and assigns the updated result back to the variable.

2. Learning Objectives

After studying this topic, learners will be able to:

  • Understand the meaning and purpose of assignment operators.
  • Assign values to variables using the = operator.
  • Identify and use Python's compound assignment operators.
  • Update numeric variables using arithmetic operations.
  • Understand the difference between assignment and equality comparison.
  • Use multiple assignment and chained assignment correctly.
  • Apply assignment operators in loops, counters, and accumulators.
  • Understand how assignment behaves with mutable and immutable objects.
  • Recognize common errors involving assignment operators.
  • Develop practical programs using assignment and compound assignment.

3. What Is an Assignment Operator?

An assignment operator assigns a value or an evaluated expression to a target, usually a variable. Python evaluates the expression on the right-hand side and assigns the resulting object to the target on the left-hand side.

Syntax

variable_name = value

Example

name = "Aarav"
age = 22
salary = 35000.50
is_student = True

print(name)
print(age)
print(salary)
print(is_student)

Output:

Aarav
22
35000.5
True

Python does not require you to declare a variable's type before assigning a value. The type is determined by the object assigned to the variable.

4. Understanding the Basic Assignment Operator (=)

The assignment operator (=) stores a reference to the evaluated right-hand-side object in the target variable. It is not the same as the mathematical equality symbol used to compare two values.

Example 1: Assigning an Integer

number = 100
print(number)

Output:

100

Example 2: Assigning a String

course = "Python Programming"
print(course)

Output:

Python Programming

Example 3: Assigning the Result of an Expression

a = 20
b = 15
total = a + b

print(total)

Output:

35

Python calculates a + b first and assigns the result to total.

Example 4: Reassigning a Variable

score = 50
print(score)

score = 80
print(score)

Output:

50
80

Reassignment changes which object the variable refers to. In this example, score first refers to the integer object representing 50 and then refers to the integer object representing 80.

5. Assignment Operator Versus Equality Operator

Beginners often confuse assignment (=) with equality comparison (==). Although their symbols look similar, they perform different tasks.

Feature Assignment (=) Equality (==)
Purpose Assigns a value to a target. Compares two values for equality.
Typical location Variable assignment statement. Conditions and expressions.
Result Updates the target binding. Produces a Boolean result, usually True or False.
Example age = 20 age == 20

Example

age = 20

print(age == 20)
print(age == 25)

Output:

True
False

The first line assigns a value to age. The expressions using == compare the current value of age with other values.

6. What Are Compound Assignment Operators?

Compound assignment operators combine an operation with assignment. They provide a compact way to update a variable based on its current value.

For example, the expression count += 1 adds one to the current value of count and assigns the updated value back to count.

For a simple numeric variable, this commonly has the same result as writing count = count + 1. However, compound assignment can behave differently for mutable objects because it may update an object in place instead of creating a new object. Therefore, the two forms are not universally interchangeable.

Basic Example

count = 10
count += 5

print(count)

Output:

15

7. Types of Compound Assignment Operators

Python supports several augmented assignment operators for arithmetic, bitwise, and related operations. The most common arithmetic compound assignment operators are listed below.

Operator Meaning Equivalent simple form Example starting with x = 10 Result
+= Add and assign x = x + 3 x += 3 13
-= Subtract and assign x = x - 3 x -= 3 7
*= Multiply and assign x = x * 3 x *= 3 30
/= Divide and assign x = x / 3 x /= 3 3.333...
//= Floor divide and assign x = x // 3 x //= 3 3
%= Calculate remainder and assign x = x % 3 x %= 3 1
**= Raise to a power and assign x = x ** 3 x **= 3 1000
&= Bitwise AND and assign x = x & 3 x = 10; x &= 3 2
|= Bitwise OR and assign x = x | 3 x = 10; x |= 3 11
^= Bitwise XOR and assign x = x ^ 3 x = 10; x ^= 3 9
<<= Left-shift and assign x = x << 1 x = 10; x <<= 1 20
>>= Right-shift and assign x = x >> 1 x = 10; x >>= 1 5
@= Matrix multiply and assign x = x @ y Depends on compatible matrix operands. Depends on operands.

Bitwise and matrix assignment operators are more specialized. Beginners should first become comfortable with the arithmetic operators, then explore bitwise operations and matrix multiplication when needed.

8. Addition Assignment Operator (+=)

The += operator adds a value to the current value or updates a compatible object, then assigns the result back to the target. It is commonly used for totals, counters, scores, and accumulators.

Example 1: Updating a Number

balance = 1000
balance += 500

print("Updated balance:", balance)

Output:

Updated balance: 1500

Example 2: Incrementing a Counter

count = 0

count += 1
count += 1
count += 1

print("Count:", count)

Output:

Count: 3

Example 3: Adding to a Running Total

total = 0
total += 100
total += 250
total += 150

print("Total:", total)

Output:

Total: 500

Example 4: Extending a List

numbers = [1, 2]
numbers += [3, 4]

print(numbers)

Output:

[1, 2, 3, 4]

For a list, += extends the existing list with the elements from the right-hand iterable. This differs from numeric addition because lists are mutable objects.

9. Subtraction Assignment Operator (-=)

The -= operator subtracts a value from the current value and assigns the result back to the variable. It is useful for reducing balances, updating inventory, tracking remaining quantities, and decrementing counters.

Example 1: Updating a Balance

balance = 2000
withdrawal = 750

balance -= withdrawal

print("Remaining balance:", balance)

Output:

Remaining balance: 1250

Example 2: Reducing Inventory

stock = 100
sold_items = 18

stock -= sold_items

print("Remaining stock:", stock)

Output:

Remaining stock: 82

Example 3: Decrementing a Counter

count = 10
count -= 1
count -= 1

print(count)

Output:

8

10. Multiplication Assignment Operator (*=)

The *= operator multiplies the current value by another value and assigns the result back to the target. It is useful for scaling values, calculating repeated growth, and updating measurements.

Example 1: Scaling a Value

number = 8
number *= 4

print(number)

Output:

32

Example 2: Calculating a Total Price

price = 250
quantity = 3

price *= quantity

print("Total price:", price)

Output:

Total price: 750

After the operation, the variable named price contains the calculated total rather than the original unit price. In larger programs, a separate variable such as total_price may communicate the meaning more clearly.

Example 3: Repeating a String

message = "Python "
message *= 3

print(message)

Output:

Python Python Python 

When the operands support sequence repetition, multiplication assignment can repeat a string or list. The repeat count must be an integer.

11. Division Assignment Operator (/=)

The /= operator divides the current value by another value and assigns the quotient back to the variable. It is often used to calculate averages, split amounts, or scale measurements down.

Example 1: Dividing a Number

number = 100
number /= 4

print(number)

Output:

25.0

Example 2: Calculating an Average

total_marks = 270
number_of_subjects = 3

total_marks /= number_of_subjects

print("Average marks:", total_marks)

Output:

Average marks: 90.0

Notice that ordinary division returns a floating-point result for these integer operands. Division assignment also raises ZeroDivisionError if the divisor is zero.

12. Floor Division Assignment Operator (//=)

The //= operator performs floor division and assigns the result back to the variable. Floor division rounds the mathematical quotient down toward negative infinity.

Example 1: Dividing into Whole Groups

items = 29
items //= 4

print(items)

Output:

7

This calculation gives the number of complete groups of four that can be made from 29 items.

Example 2: Floor Division with Negative Values

number = -17
number //= 5

print(number)

Output:

-4

The result is -4 rather than -3 because Python rounds floor division toward negative infinity.

13. Modulus Assignment Operator (%=)

The %= operator calculates the remainder after division and assigns that remainder to the target. It is useful for checking divisibility, cycling through positions, and determining leftover quantities.

Example 1: Finding the Remainder

number = 29
number %= 6

print(number)

Output:

5

Example 2: Checking Whether a Number Is Even

number = 14
number %= 2

if number == 0:
    print("Even number")
else:
    print("Odd number")

Output:

Even number

The original number is replaced by its remainder after division by two. This is suitable for the example, but if the original number is needed later, store the remainder in a separate variable.

Example 3: Finding Remaining Items

items = 37
items %= 8

print("Remaining items:", items)

Output:

Remaining items: 5

14. Exponentiation Assignment Operator (**=)

The **= operator raises the current value to a specified power and assigns the result back to the variable. It is useful for calculating powers, squares, cubes, and some mathematical growth formulas.

Example 1: Squaring a Number

number = 7
number **= 2

print(number)

Output:

49

Example 2: Calculating a Cube

number = 3
number **= 3

print(number)

Output:

27

Example 3: Exponentiation with a Negative Power

number = 2
number **= -3

print(number)

Output:

0.125

A negative exponent represents a reciprocal for a nonzero base. Be careful with very large exponents because they can produce extremely large integers or floating-point overflow, depending on the operand types and calculation.

15. Multiple Assignment in Python

Python allows multiple variables to receive values in a single statement. This feature can make initialization concise and improve readability when the values are related.

Example 1: Assigning Different Values

a, b, c = 10, 20, 30

print(a)
print(b)
print(c)

Output:

10
20
30

Example 2: Assigning the Same Value to Multiple Variables

x = y = z = 100

print(x, y, z)

Output:

100 100 100

This is chained assignment. All three names are assigned references to the same object. For immutable integers, this is generally straightforward. With mutable objects such as lists, however, all names will refer to the same list.

Example 3: Swapping Two Variables

a = 10
b = 20

a, b = b, a

print("a:", a)
print("b:", b)

Output:

a: 20
b: 10

Python evaluates the right-hand-side expressions before assigning the values to the targets. This allows the two variables to be swapped without a temporary variable.

16. Assignment with Expressions

The right-hand side of an assignment can contain mathematical expressions, function calls, or combinations of values and operators. Python evaluates the right-hand side before assigning the resulting object to the target.

price = 500
quantity = 4
discount = 100

total = price * quantity - discount

print("Total:", total)

Output:

Total: 1900

The multiplication is evaluated before subtraction. Parentheses can be used to make more complex calculations easier to understand.

Example: Updating a Variable with an Expression

score = 60
bonus = 10

score = score + bonus * 2

print(score)

Output:

80

Python first calculates bonus * 2 and then adds that result to the original score.

17. Compound Assignment Operators Inside Loops

Compound assignment operators are frequently used in loops because they allow variables to be updated repeatedly. Common examples include counting iterations, accumulating totals, and multiplying a running result.

Example 1: Adding Numbers with a Loop

total = 0

for number in range(1, 6):
    total += number

print("Sum:", total)

Output:

Sum: 15

During each iteration, total += number adds the current number to the running total.

Example 2: Counting Items

count = 0

for item in ["pen", "book", "bag", "pencil"]:
    count += 1

print("Number of items:", count)

Output:

Number of items: 4

Example 3: Calculating a Factorial

number = 5
factorial = 1

for value in range(1, number + 1):
    factorial *= value

print("Factorial:", factorial)

Output:

Factorial: 120

The expression factorial *= value multiplies the running result by the current loop value.

18. Assignment and Mutable Objects

Python variables refer to objects. Assignment does not automatically create a separate copy of an object. If two variables refer to the same mutable object, such as a list or dictionary, modifying that object through one variable can be visible through the other.

Example 1: Chained Assignment with a List

first = second = [1, 2, 3]

first.append(4)

print(first)
print(second)

Output:

[1, 2, 3, 4]
[1, 2, 3, 4]

Both variables refer to the same list. The call to append() modifies that shared list.

Example 2: Compound Assignment with a List

first = [1, 2]
second = first

first += [3, 4]

print(first)
print(second)

Output:

[1, 2, 3, 4]
[1, 2, 3, 4]

For lists, += normally extends the existing list in place. Since first and second refer to the same list, both names show the updated contents.

Example 3: Reassignment Versus In-Place Update

first = [1, 2]
second = first

first = first + [3, 4]

print(first)
print(second)

Output:

[1, 2, 3, 4]
[1, 2]

In this case, first + [3, 4] creates a new list and the name first is rebound to that new list. The original list referenced by second remains unchanged.

This difference is important: augmented assignment can use an object's in-place operation when supported, while ordinary assignment with an expression may create a new object. The precise behavior depends on the object type.

19. Assignment with Immutable Objects

Immutable objects cannot be changed in place. Common examples include integers, floats, strings, and tuples. When a compound assignment operation is performed on an immutable object, the operation generally creates or calculates a new value and rebinds the variable to it.

Example

number = 10
another_number = number

number += 5

print(number)
print(another_number)

Output:

15
10

The integer value associated with number is updated by rebinding the variable to the result of the addition. The name another_number continues to refer to the original integer value.

20. The Walrus Operator (:=)

Python also provides the assignment expression operator, commonly called the walrus operator (:=). It assigns a value to a name as part of a larger expression. Unlike the ordinary assignment statement, it can be used inside expressions, including certain conditions and loops.

Example: Assignment Inside a Condition

if (length := len("Python")) > 5:
    print("Length:", length)

Output:

Length: 6

The expression assigns the length of the string to length and then compares it with 5.

The walrus operator is useful in selected situations, but it is not a compound arithmetic assignment operator. Use it when it improves clarity, and avoid unnecessarily complex expressions.

21. Common Mistakes When Using Assignment Operators

Mistake Why It Happens Correct Approach
Using = in a comparison Confusing assignment with equality testing. Use == to compare values.
Using an undefined variable The variable was never assigned before it was read. Initialize the variable before using it.
Using a compound operator with incompatible types The operands do not support the requested operation. Check the data types and convert values where appropriate.
Dividing by zero with /= or //= The divisor evaluates to zero. Validate the divisor before the operation.
Unexpected changes to a shared list Two variables refer to the same mutable object. Use a copy if an independent list is required.
Confusing += with ordinary addition and reassignment In-place behavior may matter for mutable objects. Understand the type-specific behavior of augmented assignment.
Overwriting a useful value A variable is reused for a different purpose. Use meaningful variable names and separate variables when appropriate.
Using an invalid augmented assignment expression Writing the operator in the wrong order, such as + =. Write the operator without a space between its symbols, such as +=.

22. Handling Errors in Assignment Calculations

When assignment operators are used with user input, programs should validate the input and handle errors gracefully.

Example: Safe Division Assignment

try:
    number = float(input("Enter a number: "))
    divisor = float(input("Enter the divisor: "))

    if divisor == 0:
        print("Error: divisor cannot be zero.")
    else:
        number /= divisor
        print("Updated result:", number)

except ValueError:
    print("Error: please enter valid numeric values.")

Explanation:

  • input() collects values from the user.
  • float() converts the entered strings to numeric values.
  • The condition checks whether the divisor is zero.
  • The /= operator updates the variable when the operation is valid.
  • The except ValueError block handles invalid numeric input.

23. Practical Example: Shopping Cart Total

A shopping cart can use assignment and compound assignment operators to calculate the total price of multiple products.

Program

total = 0

item1_price = 250
item1_quantity = 2
total += item1_price * item1_quantity

item2_price = 120
item2_quantity = 3
total += item2_price * item2_quantity

discount = 100
total -= discount

print("Final cart total:", total)

Output:

Final cart total: 760

Explanation:

  • The total starts at zero.
  • The first product's price is multiplied by its quantity and added to the total.
  • The second product's cost is added to the running total.
  • The discount is subtracted using -=.
  • The final amount is displayed.

24. Practical Example: Bank Account Balance

Compound assignment operators can model simple account transactions in an educational program. A real banking application requires additional security, validation, transaction handling, and precision rules.

Program

balance = 5000

deposit = 1500
balance += deposit
print("After deposit:", balance)

withdrawal = 1200

if withdrawal <= balance:
    balance -= withdrawal
    print("After withdrawal:", balance)
else:
    print("Insufficient balance")

print("Final balance:", balance)

Output:

After deposit: 6500
After withdrawal: 5300
Final balance: 5300

The += operator adds the deposit to the current balance, while -= subtracts a valid withdrawal.

25. Practical Example: Updating Product Inventory

Inventory systems need to increase stock when new items arrive and decrease stock when items are sold.

Program

stock = 50

new_stock = 20
stock += new_stock
print("Stock after delivery:", stock)

sold = 15

if sold <= stock:
    stock -= sold
    print("Stock after sale:", stock)
else:
    print("Not enough stock")

print("Available stock:", stock)

Output:

Stock after delivery: 70
Stock after sale: 55
Available stock: 55

This example demonstrates how assignment operators can simplify updates in inventory tracking and stock management applications.

26. Practical Example: Compound Assignment Calculator

The following program demonstrates multiple compound assignment operators in one example.

Program

number = 12
print("Initial value:", number)

number += 8
print("After += 8:", number)

number -= 5
print("After -= 5:", number)

number *= 2
print("After *= 2:", number)

number /= 3
print("After /= 3:", number)

number **= 2
print("After **= 2:", number)

Output:

Initial value: 12
After += 8: 20
After -= 5: 15
After *= 2: 30
After /= 3: 10.0
After **= 2: 100.0

The example illustrates how each operator uses the value produced by the previous operation. Once /= is used, the variable holds a floating-point result, so the later exponentiation also produces a float.

27. Best Practices for Assignment Operators

  • Use descriptive names such as total_price, remaining_stock, and student_count.
  • Initialize variables before using them in calculations.
  • Use = for assignment and == for equality comparisons.
  • Use compound assignment operators when they make an update easier to read.
  • Do not use compound assignment merely to shorten code if it makes the logic confusing.
  • Validate values before division or modulus operations.
  • Choose appropriate numeric types for the task, particularly when working with financial values.
  • Understand the difference between mutable and immutable objects.
  • Use copying when separate mutable collections are required.
  • Keep the original value in a separate variable if it will be needed later.
  • Test edge cases such as zero, negative numbers, empty lists, and invalid user input.
  • Use comments to explain non-obvious calculations or updates.

28. Practice Exercises

Beginner-Level Exercises

  1. Create a variable called age and assign it your age.
  2. Assign two numbers to variables and calculate their sum using =.
  3. Initialize a counter at zero and increase it three times using +=.
  4. Create a balance variable and subtract a withdrawal using -=.
  5. Assign values to three variables in a single statement.

Intermediate-Level Exercises

  1. Start with a number and apply +=, -=, and *= sequentially. Display the result after every operation.
  2. Calculate a student's average by using /= on the total marks.
  3. Use //= and %= to find the quotient and remainder of a division.
  4. Calculate the square of a number using **=.
  5. Build a shopping cart program that uses += to accumulate product totals and -= to apply a discount.

Advanced-Level Exercises

  1. Build an inventory program that accepts deliveries and sales, updates stock, and prevents the stock value from becoming negative.
  2. Create a program that calculates a running total from a sequence of user-entered numbers.
  3. Compare the behavior of items = items + [4] and items += [4] when another variable refers to the same list.
  4. Use chained assignment with a list and explain why changing the list through one variable affects the other variable.
  5. Create a simple account simulator that processes deposits and valid withdrawals using compound assignment operators.

29. Mini Project: Personal Expense Tracker

Project Objective: Create a small expense tracker that starts with a budget, adds income, subtracts expenses, and displays the remaining balance.

Project Code

try:
    budget = float(input("Enter your starting budget: "))
    income = float(input("Enter additional income: "))
    expense1 = float(input("Enter first expense: "))
    expense2 = float(input("Enter second expense: "))

    if budget < 0 or income < 0 or expense1 < 0 or expense2 < 0:
        print("Values cannot be negative.")
    else:
        balance = budget
        balance += income
        balance -= expense1
        balance -= expense2

        print("Starting budget:", budget)
        print("Additional income:", income)
        print("Total expenses:", expense1 + expense2)
        print("Remaining balance:", balance)

        if balance < 0:
            print("Warning: spending exceeds available funds.")

except ValueError:
    print("Please enter valid numeric amounts.")

Sample Input

Enter your starting budget: 5000
Enter additional income: 1000
Enter first expense: 1200
Enter second expense: 800

Sample Output

Starting budget: 5000.0
Additional income: 1000.0
Total expenses: 2000.0
Remaining balance: 4000.0

Concepts Practiced

  • Basic assignment using =.
  • Adding income using +=.
  • Subtracting expenses using -=.
  • Input conversion with float().
  • Input validation and exception handling.
  • Using conditional statements to display a warning.

30. Interview Questions and Answers

Q1. What is an assignment operator in Python?

Answer: An assignment operator assigns a value or evaluated expression to a target. The most common assignment operator is =.

Q2. What is the difference between = and ==?

Answer: The = operator assigns a value, whereas == compares two values and produces a Boolean result.

Q3. What are compound assignment operators?

Answer: Compound assignment operators combine an operation with assignment. Examples include +=, -=, *=, /=, //=, %=, and **=.

Q4. What is the difference between x += 5 and x = x + 5?

Answer: For a simple numeric variable, both normally produce the same resulting value. However, augmented assignment may update mutable objects in place and can differ from ordinary addition followed by assignment.

Q5. What is the result of this code?

x = 10
x += 5
x *= 2
print(x)

Answer: The result is 30. First, 5 is added to 10, producing 15. Then 15 is multiplied by 2.

Q6. Can multiple variables be assigned in one statement?

Answer: Yes. For example, a, b, c = 10, 20, 30 assigns each corresponding value to a variable.

Q7. What is chained assignment?

Answer: Chained assignment assigns the same object to multiple targets in one statement, such as a = b = c = 0. With mutable objects, this means all targets refer to the same object.

Q8. What happens when /= is used with integer values?

Answer: It performs true division and ordinarily stores a floating-point result. For example, if x = 10, then x /= 2 makes x equal to 5.0.

Q9. What is the purpose of **=?

Answer: It raises a variable's current value to a specified power and assigns the result back. For example, x = 3; x **= 2 results in 9.

Q10. What is the difference between += on integers and lists?

Answer: For integers, += calculates a new numeric value and rebinds the variable. For lists, it normally extends the existing list in place with elements from the right-hand iterable.

Q11. What is the walrus operator in Python?

Answer: The walrus operator (:=) is an assignment expression that assigns a value to a name as part of a larger expression. It is different from compound arithmetic assignment operators.

Q12. Why can two variables show the same updated list after an operation?

Answer: Both variables may refer to the same mutable list. When the list is modified in place, the change is visible through every reference to that list.

31. Quick Revision Checklist

  • =: Assigns a value or expression result to a target.
  • +=: Adds and assigns.
  • -=: Subtracts and assigns.
  • *=: Multiplies and assigns.
  • /=: Performs true division and assigns.
  • //=: Performs floor division and assigns.
  • %=: Calculates the remainder and assigns.
  • **=: Raises a value to a power and assigns.
  • Multiple assignment: Assigns values to several targets in one statement.
  • Chained assignment: Assigns the same object to multiple targets.
  • Mutable objects: Multiple variables may refer to one shared object.
  • Equality comparison: Use ==, not =, to compare values.
  • Error handling: Validate input and avoid division by zero.

32. Conclusion

Assignment and compound assignment operators are essential tools for storing values and updating data in Python. The basic assignment operator (=) binds a variable to an object, while compound assignment operators provide concise ways to perform operations and update the target.

These operators are widely used in loops, counters, running totals, expense calculations, inventory management, and many other programming tasks. Understanding how assignment interacts with mutable objects, numeric types, and expressions helps prevent common mistakes and makes code more predictable.

Practice the examples and exercises in this lesson, then build small projects to develop confidence with these operators.

Continue learning through the Python Training Course at JustAcademy, register for a course demo, or visit the JustAcademy homepage.

whatsapp